package Stack;

import java.util.Iterator;
public class LinkedListStack<E> implements StackInterface<E>,Iterable<E>{

    static class Node<E> {
        public E value;
        Node<E> next;

        public Node() {
        }

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }

    private int size;
    private final int capacity;
    private final Node<E> sentry;

    public LinkedListStack(int capacity) {
        this.capacity = capacity;
        this.sentry = new Node<>(null,null);
    }


    @Override
    public boolean push(E value) {

        if (isFull()) {
            System.out.println("栈容量满了！！！");
            return false;
        }
        sentry.next = new Node<>(value,sentry.next);
        size++;
        return true;
    }

    @Override
    public E pop() {
        if (isEmpty()) {
            return null;
        }
        Node<E> first = sentry.next;
        sentry.next = first.next;
        size--;
        return first.value;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        Node<E> first = sentry.next;
        return first.value;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
        //return sentry.next == null;
    }

    @Override
    public boolean isFull() {
        return size == capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node<E> p = sentry.next;
            @Override
            public boolean hasNext() {
                return p != null;
            }

            @Override
            public E next() {
                E key = p.value;
                p = p.next;
                return key;
            }
        };
    }
}
